#!/usr/bin/env python
"""
初始化数据脚本
"""
import os
import sys
import django
from django.contrib.auth import get_user_model

# 设置Django环境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'inter_api.settings')
django.setup()

from students.models import School, Major, Grade, Class
from accounts.models import Permission, RolePermission
from interviews.models import InterviewCategory
from file_management.models import FileCategory
from notifications.models import NotificationTemplate

User = get_user_model()


def create_superuser():
    """创建超级用户"""
    if not User.objects.filter(username='admin').exists():
        User.objects.create_superuser(
            username='admin',
            email='admin@example.com',
            password='admin123',
            first_name='系统',
            last_name='管理员',
            role='admin'
        )
        print("✓ 创建超级用户: admin / admin123")


def create_test_users():
    """创建测试用户"""
    # 创建测试老师
    if not User.objects.filter(username='teacher001').exists():
        User.objects.create_user(
            username='teacher001',
            email='teacher001@example.com',
            password='teacher123',
            first_name='张',
            last_name='老师',
            role='teacher'
        )
        print("✓ 创建测试老师: teacher001 / teacher123")
    
    # 创建测试学生
    if not User.objects.filter(username='2023001001').exists():
        User.objects.create_user(
            username='2023001001',
            email='student001@example.com',
            password='student123',
            first_name='李',
            last_name='同学',
            role='student'
        )
        print("✓ 创建测试学生: 2023001001 / student123")


def create_school_structure():
    """创建学校组织结构"""
    # 创建学校
    school, created = School.objects.get_or_create(
        name='鸥鹏科技大学',
        defaults={
            'code': 'OPTU',
            'address': '北京市海淀区中关村大街1号',
            'phone': '010-12345678',
            'website': 'https://www.optu.edu.cn',
            'description': '鸥鹏科技大学是一所以信息技术为特色的综合性大学。'
        }
    )
    if created:
        print("✓ 创建学校: 鸥鹏科技大学")
    
    # 创建专业
    majors_data = [
        {'name': '计算机科学与技术', 'code': 'CS', 'degree_type': 'bachelor'},
        {'name': '软件工程', 'code': 'SE', 'degree_type': 'bachelor'},
        {'name': '数据科学与大数据技术', 'code': 'DS', 'degree_type': 'bachelor'},
        {'name': '人工智能', 'code': 'AI', 'degree_type': 'bachelor'},
    ]
    
    for major_data in majors_data:
        major, created = Major.objects.get_or_create(
            school=school,
            code=major_data['code'],
            defaults=major_data
        )
        if created:
            print(f"✓ 创建专业: {major.name}")
        
        # 为每个专业创建年级
        for year in [2021, 2022, 2023, 2024]:
            grade, created = Grade.objects.get_or_create(
                major=major,
                year=year,
                defaults={'name': f'{year}级'}
            )
            if created:
                print(f"  ✓ 创建年级: {major.name} {year}级")
            
            # 为每个年级创建班级
            for class_num in [1, 2]:
                class_obj, created = Class.objects.get_or_create(
                    grade=grade,
                    class_number=class_num,
                    defaults={'name': f'{class_num}班'}
                )
                if created:
                    print(f"    ✓ 创建班级: {major.name} {year}级 {class_num}班")


def create_permissions():
    """创建权限"""
    permissions_data = [
        # 用户管理权限
        {'name': '查看用户', 'codename': 'view_user', 'module': 'accounts'},
        {'name': '添加用户', 'codename': 'add_user', 'module': 'accounts'},
        {'name': '修改用户', 'codename': 'change_user', 'module': 'accounts'},
        {'name': '删除用户', 'codename': 'delete_user', 'module': 'accounts'},
        
        # 学生管理权限
        {'name': '查看学生', 'codename': 'view_student', 'module': 'students'},
        {'name': '添加学生', 'codename': 'add_student', 'module': 'students'},
        {'name': '修改学生', 'codename': 'change_student', 'module': 'students'},
        {'name': '删除学生', 'codename': 'delete_student', 'module': 'students'},
        
        # 简历管理权限
        {'name': '查看简历', 'codename': 'view_resume', 'module': 'resume'},
        {'name': '审核简历', 'codename': 'review_resume', 'module': 'resume'},
        
        # 面试管理权限
        {'name': '查看面试', 'codename': 'view_interview', 'module': 'interviews'},
        {'name': '安排面试', 'codename': 'schedule_interview', 'module': 'interviews'},
        {'name': '评价面试', 'codename': 'evaluate_interview', 'module': 'interviews'},
        
        # 岗位管理权限
        {'name': '查看岗位', 'codename': 'view_job', 'module': 'jobs'},
        {'name': '发布岗位', 'codename': 'publish_job', 'module': 'jobs'},
        {'name': '审核申请', 'codename': 'review_application', 'module': 'jobs'},
    ]
    
    for perm_data in permissions_data:
        permission, created = Permission.objects.get_or_create(
            codename=perm_data['codename'],
            defaults=perm_data
        )
        if created:
            print(f"✓ 创建权限: {permission.name}")


def create_role_permissions():
    """创建角色权限关联"""
    # 管理员拥有所有权限
    admin_permissions = Permission.objects.all()
    for permission in admin_permissions:
        RolePermission.objects.get_or_create(
            role='admin',
            permission=permission
        )
    print("✓ 配置管理员权限")
    
    # 老师权限
    teacher_permission_codes = [
        'view_user', 'view_student', 'add_student', 'change_student',
        'view_resume', 'review_resume', 'view_interview', 'schedule_interview',
        'evaluate_interview', 'view_job', 'review_application'
    ]
    teacher_permissions = Permission.objects.filter(codename__in=teacher_permission_codes)
    for permission in teacher_permissions:
        RolePermission.objects.get_or_create(
            role='teacher',
            permission=permission
        )
    print("✓ 配置老师权限")
    
    # 学生权限
    student_permission_codes = ['view_student', 'view_resume', 'view_interview', 'view_job']
    student_permissions = Permission.objects.filter(codename__in=student_permission_codes)
    for permission in student_permissions:
        RolePermission.objects.get_or_create(
            role='student',
            permission=permission
        )
    print("✓ 配置学生权限")


def create_interview_categories():
    """创建面试分类"""
    categories = [
        {'name': '技术面试', 'description': '考察专业技术能力'},
        {'name': '行为面试', 'description': '考察行为表现和软技能'},
        {'name': '综合面试', 'description': '综合考察各方面能力'},
        {'name': '英语面试', 'description': '考察英语沟通能力'},
    ]
    
    for cat_data in categories:
        category, created = InterviewCategory.objects.get_or_create(
            name=cat_data['name'],
            defaults=cat_data
        )
        if created:
            print(f"✓ 创建面试分类: {category.name}")


def create_file_categories():
    """创建文件分类"""
    categories = [
        {
            'name': '简历文件',
            'description': '学生简历相关文件',
            'allowed_extensions': '.pdf,.doc,.docx',
            'max_file_size': 5242880  # 5MB
        },
        {
            'name': '证书文件',
            'description': '各类证书文件',
            'allowed_extensions': '.pdf,.jpg,.jpeg,.png',
            'max_file_size': 10485760  # 10MB
        },
        {
            'name': '头像图片',
            'description': '用户头像图片',
            'allowed_extensions': '.jpg,.jpeg,.png,.gif',
            'max_file_size': 2097152  # 2MB
        },
    ]
    
    for cat_data in categories:
        category, created = FileCategory.objects.get_or_create(
            name=cat_data['name'],
            defaults=cat_data
        )
        if created:
            print(f"✓ 创建文件分类: {category.name}")


def create_notification_templates():
    """创建通知模板"""
    templates = [
        {
            'name': '简历审核通过',
            'notification_type': 'resume',
            'title_template': '简历审核通过通知',
            'content_template': '恭喜！您的简历已通过审核，可以开始投递岗位了。'
        },
        {
            'name': '简历需要修改',
            'notification_type': 'resume',
            'title_template': '简历需要修改',
            'content_template': '您的简历需要修改，请根据审核意见进行调整后重新提交。'
        },
        {
            'name': '面试安排通知',
            'notification_type': 'interview',
            'title_template': '面试安排通知',
            'content_template': '您有一场面试已安排，请准时参加。'
        },
        {
            'name': '岗位申请结果',
            'notification_type': 'job',
            'title_template': '岗位申请结果通知',
            'content_template': '您的岗位申请已有结果，请查看详情。'
        },
    ]
    
    for template_data in templates:
        template, created = NotificationTemplate.objects.get_or_create(
            name=template_data['name'],
            defaults=template_data
        )
        if created:
            print(f"✓ 创建通知模板: {template.name}")


def main():
    """主函数"""
    print("开始初始化数据...")
    
    try:
        create_superuser()
        create_test_users()
        create_school_structure()
        create_permissions()
        create_role_permissions()
        create_interview_categories()
        create_file_categories()
        create_notification_templates()
        
        print("\n✅ 数据初始化完成！")
        print("\n测试账号:")
        print("管理员: admin / admin123")
        print("老师: teacher001 / teacher123")
        print("学生: 2023001001 / student123")
        
    except Exception as e:
        print(f"\n❌ 初始化失败: {e}")
        sys.exit(1)


if __name__ == '__main__':
    main()
